import { CPosition } from 'stores/editorModels';

/**
 * 矩形边界检测-中心点判断法
 * @param {*} frameRect
 * @param {*} itemRect
 */
export function checkByPointInRect (frameRect: CPosition, itemRect: CPosition) {
  let  x = itemRect.x + itemRect.w / 2;
  let  y = itemRect.y + itemRect.h / 2;
  if (x > frameRect.x && y > frameRect.y && x < (frameRect.x + frameRect.w) && y < (frameRect.y + frameRect.h)) {
    return true;
  } else {
    return false;
  }
}

/**
 * 矩形边界检测-碰撞检测法
 * 两个矩形中心点在x方向的距离的绝对值小于等于矩形宽度和的二分之一，同时y方向的距离的绝对值小于等于矩形高度和的二分之一
 * @param {*} frameRect
 * @param {*} itemRect
 */
export function checkByRectCollisionDetection (frameRect: CPosition, itemRect: CPosition) {
  let x1 = frameRect.x + frameRect.w / 2;
  let y1 = frameRect.y + frameRect.h / 2;
  let w1 = frameRect.w;
  let h1 = frameRect.h;
  let x2 = itemRect.x + itemRect.w / 2;
  let y2 = itemRect.y + itemRect.h / 2;
  let w2 = itemRect.w;
  let h2 = itemRect.h;
  if (Math.abs(x1 - x2) < ((w1 + w2) / 2) && Math.abs(y1 - y2) < ((h1 + h2) / 2)) {
    return true;
  } else {
    return false;
  }
}

//有数序列，二分法查找
export function binarySearch (list: number[], kv: number): number {
  let low = 0;
  let high = list.length - 1;
  let mid = 0;
  while (low <= high) {
    mid = Math.floor((low + high) / 2);
    if (list[mid] === kv) {
      return mid;
    } else if (list[mid] < kv) {
      low = mid + 1;
    } else if (list[mid] > kv) {
      high = mid - 1;
    } else {
      return -1;
    }
  }
  return -1;
}

// 查找最小值
export function searchMin (list: number[]): number {
  let min = list[0];
  let i = 0;
  for (i = 1; i < list.length; i++) {
    if (list[i] < min) {
      min = list[i];
    }
  }
  return min;
}

// 查找最大值
export function searchMax (list: number[]): number {
  let max = list[0];
  let i = 0;
  for (i = 1; i < list.length; i++) {
    if (list[i] > max) {
      max = list[i];
    }
  }
  return max;
}

// 查找最小值,返回数组下标
export function findArrayMin (list: number[]): number {
  if (list.length < 1) {
    return -1;
  } else {
    let min = list[0];
    let i = 0;
    let j = 0;
    for (i = 1; i < list.length; i++) {
      if (list[i] < min) {
        min = list[i];
        j = i;
      }
    }
    return j;
  }
}

// 查找最大值,返回数组下标
export function findArrayMax (list: number[]): number {
  if (list.length < 1) {
    return -1;
  } else {
    let max = list[0];
    let i = 0;
    let j = 0;
    for (i = 1; i < list.length; i++) {
      if (list[i] > max) {
        max = list[i];
        j = i;
      }
    }

    return j;
  }
}

//arraybuffer转换为字符串
export function arrayBufferToHexString (buffer: ArrayBuffer) {
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' +
    x.toString(16)).slice(-2)).join('');
}
